// pages/address/address.js
import config from '../../utils/config';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressList: [],
    originalAddressList: [],
    searchQuery: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.fetchUserAddress();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.fetchUserAddress(() => {
      wx.stopPullDownRefresh(); // 停止下拉刷新
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 简单的搜索
  onSearchInput(e) {
    const query = e.detail.value.toLowerCase();
    const filteredList = this.data.originalAddressList.filter(item => {
      return item.name.toLowerCase().includes(query) || 
             item.phone.includes(query) || 
             item.detailAddress.toLowerCase().includes(query);
    });
    this.setData({ searchQuery: query, addressList: filteredList });
  },

  clearSearch() {
    this.setData({ 
      searchQuery: '',
      addressList: this.data.originalAddressList
    });
  },

  radioChange(e) {
    const selectedValue = e.detail.value;
    console.log('选择的地址ID为：', selectedValue);

    // 调用后端接口设置默认地址
    wx.request({
      url: `${config.baseUrl}/setDefaultAddress`,
      method: 'POST',
      header: {
        'Authorization': wx.getStorageSync('token'),
        'content-type': 'application/json'
      },
      data: {
        id: selectedValue
      },
      success: function(res) {
        if (res.statusCode === 200) {
          wx.showToast({
            title: '设置成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: '设置失败',
            icon: 'none'
          });
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  editAddress(e) {
    const addressId = e.currentTarget.dataset.id;
    
    const address = this.data.addressList.find(item => item.id === addressId);
    if (address) {
      wx.navigateTo({
        url: `/pages/saveAddress/saveAddress?address=${encodeURIComponent(JSON.stringify(address))}`
      });
    } else {
      wx.showToast({
        title: '地址信息无效',
        icon: 'none'
      });
    }
  },

  deleteAddress(e) {
    const addressId = e.currentTarget.dataset.id;
    const that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除该地址吗？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: `${config.baseUrl}/deleteAddress`,
            method: 'POST',
            header: {
              'Authorization': wx.getStorageSync('token'),
              'content-type': 'application/json'
            },
            data: {
              id: addressId
            },
            success: function(res) {
              if (res.statusCode === 200) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                that.fetchUserAddress(); // 刷新列表
              } else {
                wx.showToast({
                  title: '删除失败',
                  icon: 'none'
                });
              }
            },
            fail: function() {
              wx.showToast({
                title: '网络错误',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  addAddress() {
    wx.navigateTo({
      url: '/pages/saveAddress/saveAddress'
    });
  },

  fetchUserAddress(callback) {
    wx.request({
      url: `${config.baseUrl}/getUserAddress`,
      header: {
        'Authorization': wx.getStorageSync('token'),
        'content-type': 'application/json'
      },
      method: 'GET',
      success: (res) => {
        console.log(res);
        if (res.statusCode === 200) {
          this.setData({ 
            addressList: res.data.data,
            originalAddressList: res.data.data
          });
          console.log('Address List:', this.data.addressList);
        } else {
          wx.showToast({
            title: '获取地址失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      },
      complete: () => {
        if (callback) callback();
      }
    });
  }
})